package com.zjut.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjut.dao.UserDao;
import com.zjut.domain.User;
import com.zjut.service.impl.UserServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements UserServiceImpl {

    @Autowired
    private UserDao userDao;


    @Override
    public boolean save(User user) {return userDao.insert(user) > 0; }

    @Override
    public boolean update(User user) {return userDao.updateById(user) > 0;}

    @Override
    public boolean delete(Integer id) {return userDao.deleteById(id) > 0;}

    @Override
    public User getById(Integer id) {
        return userDao.selectById(id);
    }

    @Override
    public List<User> getAll() {
        return userDao.selectList(null);
    }

    @Override
    public User getByUsername(String username){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,username);
        return userDao.selectOne(lqw);
    }

    @Override
    public User getByUsernameAndPassword(String username,String password){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,username);
        lqw.eq(User::getPassword,password);
        return userDao.selectOne(lqw);
    }

    @Override
    public IPage<User> getPage(Integer currentPage, Integer pageSize, User user){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(user.getUsername()),User::getUsername,user.getUsername())
                .or().like(Strings.isNotEmpty(user.getName()),User::getName,user.getName())
                .or().like(Strings.isNotEmpty(user.getTelephone()),User::getTelephone,user.getTelephone());
        lqw.orderByDesc(User::getStatus,User::getUsername);
        IPage page = new Page(currentPage,pageSize);
        userDao.selectPage(page,lqw);
        return page;
    }
}
